<template>
  <view class="modern-login-container">
    <!-- 背景装饰 -->
    <view class="bg-decoration">
      <view class="bg-circle bg-circle-1"></view>
      <view class="bg-circle bg-circle-2"></view>
      <view class="bg-circle bg-circle-3"></view>
    </view>

    <!-- 主登录区域 -->
    <view class="login-main-content">
      <!-- 头部Logo区域 -->
      <view class="header-section">
        <view class="logo-area">
          <image
            class="logo-image"
            :src="globalConfig.appInfo.logo"
            mode="widthFix"
          >
          </image>
        </view>
        <view class="system-title">
          <text class="main-title">吉泰安生产物流系统</text>
          <text class="sub-title">iSteel工业互联网平台</text>
        </view>
      </view>

      <!-- 登录表单卡片 -->
      <view class="login-card">
        <view class="card-header">
          <text class="card-title">用户登录</text>
        </view>

        <view class="login-form-content">
          <view class="input-item">
            <view class="input-wrapper">
              <view class="iconfont icon-user input-icon"></view>
              <input
                v-model="loginForm.username"
                class="modern-input"
                type="text"
                placeholder="请输入账号"
                maxlength="30"
              />
            </view>
          </view>

          <view class="input-item">
            <view class="input-wrapper">
              <view class="iconfont icon-password input-icon"></view>
              <input
                v-model="loginForm.password"
                type="password"
                class="modern-input"
                placeholder="请输入密码"
                maxlength="20"
              />
            </view>
          </view>

          <view class="action-btn">
            <button @click="handleLogin" class="modern-login-btn">
              <text class="btn-text">登录</text>
              <view class="btn-loading" v-if="loading"></view>
            </button>
          </view>
        </view>
      </view>

      <!-- 网络配置选择器 -->
      <view class="network-config">
        <view class="network-header">
          <text class="network-title">网络环境</text>
          <text class="network-subtitle">Network Environment</text>
        </view>
        <view class="network-env-selector">
          <view
            class="env-item"
            v-for="(item, index) in networkOptions"
            :key="index"
            :class="{ active: selectedNetwork === item.value }"
            @click="selectNetwork(item.value)"
          >
            {{ item.label }}
          </view>
        </view>
      </view>
    </view>

    <!-- 底部版权信息 -->
    <view class="footer-section">
      <view class="company-info">
        <text class="platform-info">北京首钢吉泰安新材料有限公司</text>
        <text class="platform-info"
          >Powered by 冶金工业规划研究院 iSteel工业互联网平台</text
        >
      </view>
      <view class="footer-decoration">
        <view class="decoration-line"></view>
        <view class="decoration-dot"></view>
        <view class="decoration-line"></view>
      </view>
    </view>
  </view>
</template>

<script>
import appUpdate from "@/utils/appUpdate";

export default {
  data() {
    // 从缓存获取保存的账号密码（不获取网络配置，每次登录都需要重新选择）
    let savedCredentials = {
      username: "",
      password: "",
    };

    try {
      const savedUsername = uni.getStorageSync("savedUsername");
      const savedPassword = uni.getStorageSync("savedPassword");
      if (savedUsername && savedPassword) {
        savedCredentials.username = savedUsername;
        savedCredentials.password = savedPassword;
        console.log("已从缓存恢复账号密码");
      }
    } catch (error) {
      console.warn("读取缓存账号密码失败，使用默认值:", error);
    }

    return {
      codeUrl: "",
      captchaEnabled: true,
      globalConfig: getApp().globalData.config,
      loginForm: {
        username: savedCredentials.username,
        password: savedCredentials.password,
        captchaVerification: "",
      },
      loading: false,
      // 网络配置选项
      networkOptions: [
        { label: "工业1", value: "http://172.168.1.11:48000" },
        { label: "工业2", value: "http://172.168.1.10:48000" },
        { label: "办公", value: "http://10.76.83.96:48000" },
        { label: "其它", value: "http://192.168.8.124:48080" },
      ],
      selectedNetwork: "http://172.168.1.11:48000", // 默认选择工业1，不读取缓存
    };
  },
  methods: {
    // 登录方法
    async handleLogin() {
      if (this.loginForm.username === "") {
        this.$modal.msgError("请输入账号");
        return;
      } else if (this.loginForm.password === "") {
        this.$modal.msgError("请输入密码");
        return;
      }

      // 更新全局配置中的baseUrl
      this.updateBaseUrl(this.selectedNetwork);
      this.loading = true;
      this.$modal.loading("登录中，请耐心等待...");

      try {
        await this.pwdLogin();
      } finally {
        this.loading = false;
      }
    },

    // 更新baseUrl配置
    updateBaseUrl(url) {
      // 更新全局配置
      getApp().globalData.config.baseUrl = url;

      // 调用config.js的setBaseUrl方法保存配置（登录时保存，确保网络配置生效）
      try {
        const config = require("@/config.js");
        if (config.setBaseUrl) {
          const success = config.setBaseUrl(url);
          if (success) {
            console.log("网络配置已成功保存到config.js:", url);
          } else {
            console.warn("保存网络配置失败");
          }
        } else {
          console.warn("config.js中未找到setBaseUrl方法");
        }
      } catch (error) {
        console.error("调用config.setBaseUrl失败:", error);
      }
    },

    // 网络环境选择变化
    onNetworkChange(e) {
      this.selectedNetwork = e.detail.value;
    },

    // 选择网络环境
    selectNetwork(value) {
      this.selectedNetwork = value;
    },

    // 密码登录
    async pwdLogin() {
      try {
        await this.$store.dispatch("user/Login", this.loginForm);
        this.$modal.closeLoading();
        this.loginSuccess();
      } catch (error) {
        this.$modal.closeLoading();
        console.error("登录失败:", error);
        this.$modal.msgError("登录失败，请检查账号密码");
      }
    },

    // 登录成功后，处理函数
    async loginSuccess(result) {
      // 保存账号密码到缓存
      try {
        uni.setStorageSync("savedUsername", this.loginForm.username);
        uni.setStorageSync("savedPassword", this.loginForm.password);
        console.log("账号密码已保存到缓存");
      } catch (error) {
        console.warn("保存账号密码到缓存失败:", error);
      }

      // 设置用户信息
      try {
        await this.$store.dispatch("user/GetInfo");
        // 登录成功后立即检测版本更新并启动静默下载（说明书 3.1）
        // 不等待下载完成，立即跳转到首页
        this.checkUpdateAfterLogin(true); // true表示启用静默下载

        // 登录成功后自动跳转到smart页面
        console.log("登录成功，自动跳转到smart页面");
        this.$modal.msgSuccess("登录成功，正在跳转...");

        // 延迟一点跳转，让用户看到成功提示
        setTimeout(() => {
          this.$tab.reLaunch("/pages/smart/index");
        }, 1000);
      } catch (error) {
        console.error("获取用户信息失败:", error);
        this.$modal.msgError("获取用户信息失败，请重试");
      }
    },

    // 登录后版本检测（支持静默下载）
    async checkUpdateAfterLogin(silentDownload = false) {
      try {
        console.log("开始登录后版本检测", silentDownload ? "(静默模式)" : "");
        // 只在App环境中进行版本检测
        // if (!this.checkAppEnvironment()) {
        //   console.log("非App环境，跳过版本检测");
        //   return { hasUpdate: false };
        // }

        // 使用新的版本更新服务
        const updateResult = await appUpdate.checkAppUpdate({
          silent: true, // 静默检测
          silentDownload: silentDownload, // 静默下载
          autoInstall: false, // 禁止自动安装，需要用户手动确认
          onComplete: (result) => {
            if (result.hasUpdate && !result.silentDownload) {
              console.log("发现新版本，已提示用户更新");
            } else if (result.hasUpdate && result.silentDownload) {
              console.log(
                "发现新版本，已启动静默下载（下载完成后将提示用户手动安装）"
              );
            }

            // 处理静默下载完成后的用户确认
            if (result.downloadComplete && result.filePath) {
              if (result.userConfirmedInstall === true) {
                console.log("用户确认立即安装新版本");
                // 用户选择立即安装，执行安装流程
                this.installApkAfterLogin(result.filePath);
              } else if (result.userConfirmedInstall === false) {
                console.log("用户选择稍后安装新版本");
                // 用户选择稍后安装，显示提示信息
                uni.showToast({
                  title: "已选择稍后安装，可在我页面手动更新",
                  icon: "none",
                  duration: 3000,
                });
              }
            }
          },
        });

        return updateResult;
      } catch (e) {
        // 静默吞掉异常，不影响登录主流程
        console.warn("登录后版本检测异常:", e);
        return { hasUpdate: false, error: e.message };
      }
    },

    // 下载+安装（登录后专用）
    async doDownloadAfterLogin(item) {
      // 检查运行环境
      const isApp = this.checkAppEnvironment();

      if (!isApp) {
        // Web环境 - 提供下载链接
        this.showWebDownloadDialog(item);
        return;
      }

      // App环境 - 使用原生下载
      await this.downloadInAppAfterLogin(item);
    },

    // 检查是否在App环境中
    checkAppEnvironment() {
      // 检查plus对象
      if (typeof plus === "undefined") {
        return false;
      }

      // 检查运行时环境
      if (!plus.runtime) {
        return false;
      }

      // 检查平台信息
      const systemInfo = uni.getSystemInfoSync();
      return (
        systemInfo.platform !== "web" && systemInfo.platform !== "devtools"
      );
    },

    // Web环境下载对话框（取消确认，直接开始下载）
    showWebDownloadDialog(item) {
      // 显示下载开始提示
      this.$modal.showCustomToast("开始下载新版本，请稍候...", "info");
      // 直接开始App内下载，不显示确认对话框
      this.downloadInAppAfterLogin(item);
    },

    // App环境下载（登录后专用）
    async downloadInAppAfterLogin(item) {
      console.log("开始下载App内更新包:", item);
      this.$modal.loading("准备下载，请稍候...");

      try {
        const downloadTask = uni.downloadFile({
          url: item.pkgUrl,
          success: (res) => {
            if (res.statusCode === 200) {
              this.$modal.closeLoading();
              // 下载完成后，显示确认安装对话框
              this.showInstallConfirmDialogAfterLogin(res.tempFilePath, item);
            } else {
              this.$modal.closeLoading();
              this.$modal.showCustomToast(
                `下载失败：服务器错误(${res.statusCode})`,
                "error"
              );
            }
          },
          fail: (err) => {
            this.$modal.closeLoading();
            console.error("下载失败:", err);
            this.$modal.showCustomToast("下载失败，请检查网络连接", "error");
          },
        });

        // // 实时进度条
        // downloadTask.onProgressUpdate(({ progress }) => {
        //   uni.showLoading({ title: `下载中 ${progress}%...` });
        // });
      } catch (error) {
        this.$modal.closeLoading();
        console.error("下载过程异常:", error);
        this.$modal.showCustomToast("下载异常，请重试", "error");
      }
    },

    // 显示安装确认对话框（登录后专用）
    showInstallConfirmDialogAfterLogin(tempFilePath, item) {
      const sizeStr = this.formatSize(item.pkgSize * 1024 * 1024);
      uni.showModal({
        title: "下载完成",
        content: `APK文件下载完成！\n文件大小：${sizeStr}\n\n是否立即安装新版本？`,
        showCancel: true,
        confirmText: "立即安装",
        cancelText: "取消安装",
        success: (res) => {
          if (res.confirm) {
            // 用户确认安装
            this.installApkAfterLogin(tempFilePath);
          } else {
            // 用户选择取消安装
            uni.showToast({
              title: "已取消安装，下载的文件已保存",
              icon: "none",
              duration: 3000,
            });
            console.log("用户取消安装，下载的APK文件路径:", tempFilePath);
          }
        },
      });
    },
    // 安装APK文件（登录后专用）
    installApkAfterLogin(tempFilePath) {
      this.$modal.loading("正在安装，请稍候...");

      try {
        // 检查plus是否可用
        if (typeof plus !== "undefined" && plus.runtime) {
          plus.runtime.install(
            tempFilePath,
            {},
            () => {
              this.$modal.closeLoading();
              // 安装成功，询问是否重启应用
              this.$modal
                .alert({
                  title: "🎉 安装成功",
                  content: "新版本安装成功！是否立即重启应用以体验最新功能？",
                  confirmText: "🔄 立即重启",
                  cancelText: "⏰ 稍后重启",
                  showCancel: true,
                  confirmColor: "#10b981",
                  cancelColor: "#64748b",
                })
                .then((restartRes) => {
                  if (restartRes.confirm) {
                    // 重启应用
                    plus.runtime.restart();
                  } else {
                    this.$modal.showCustomToast(
                      "安装完成，请手动重启应用",
                      "info"
                    );
                  }
                });
            },
            (error) => {
              this.$modal.closeLoading();
              console.error("安装失败:", error);
              this.$modal.alert({
                title: "❌ 安装失败",
                content: `安装失败：${error.message}\n\n请检查文件完整性或重新下载`,
                confirmText: "我知道了",
                showCancel: false,
                confirmColor: "#ef4444",
              });
            }
          );
        } else {
          this.$modal.closeLoading();
          this.$modal.showCustomToast(
            "安装环境异常，请在正确的App环境中使用",
            "warning"
          );
        }
      } catch (error) {
        this.$modal.closeLoading();
        console.error("安装过程异常:", error);
        this.$modal.showCustomToast("安装异常，请重试", "error");
      }
    },

    // 工具：格式化文件大小
    formatSize(byte) {
      if (!byte) return "0 B";
      const k = 1024;
      const sizes = ["B", "KB", "MB", "GB"];
      const i = Math.floor(Math.log(byte) / Math.log(k));
      return (byte / Math.pow(k, i)).toFixed(1) + " " + sizes[i];
    },
  },
};
</script>

<style lang="scss" scoped>
page {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
  overflow: hidden;
}

.modern-login-container {
  position: relative;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 40rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  overflow: hidden;

  // 背景装饰
  .bg-decoration {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1;
    pointer-events: none;

    .bg-circle {
      position: absolute;
      border-radius: 50%;
      background: linear-gradient(
        135deg,
        rgba(59, 130, 246, 0.1) 0%,
        rgba(147, 51, 234, 0.1) 100%
      );
      filter: blur(40px);

      &.bg-circle-1 {
        width: 300rpx;
        height: 300rpx;
        top: 10%;
        left: -150rpx;
        animation: float 6s ease-in-out infinite;
      }

      &.bg-circle-2 {
        width: 200rpx;
        height: 200rpx;
        top: 60%;
        right: -100rpx;
        animation: float 8s ease-in-out infinite reverse;
      }

      &.bg-circle-3 {
        width: 150rpx;
        height: 150rpx;
        bottom: 20%;
        left: 50%;
        animation: float 10s ease-in-out infinite;
      }
    }
  }

  // 主登录内容
  .login-main-content {
    position: relative;
    z-index: 2;
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    padding: 120rpx 60rpx 0;
    margin-top: 10px;
    padding-top: 20px;
  }

  // 头部区域
  .header-section {
    text-align: center;
    margin-bottom: 30rpx;

    .logo-area {
      margin-bottom: 20rpx;

      .logo-image {
        width: 100rpx;
        height: 100rpx;
        border-radius: 20rpx;
        box-shadow: 0 6rpx 18rpx rgba(0, 0, 0, 0.2);
        background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
      }
    }

    .system-title {
      .main-title {
        display: block;
        font-size: 42rpx;
        font-weight: 700;
        color: #ffffff;
        margin-bottom: 8rpx;
        letter-spacing: 1rpx;
      }

      .sub-title {
        display: block;
        font-size: 24rpx;
        color: #f8f9fa;
        font-weight: 400;
        letter-spacing: 1rpx;
      }
    }
  }

  // 登录卡片
  .login-card {
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(20px);
    border-radius: 24rpx;
    border: 1px solid rgba(255, 255, 255, 0.1);
    padding: 40rpx 32rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.3);

    .card-header {
      text-align: center;
      margin-bottom: 40rpx;

      .card-title {
        display: block;
        font-size: 36rpx;
        font-weight: 600;
        color: #2c3e50;
        margin-bottom: 8rpx;
      }

      .card-subtitle {
        display: block;
        font-size: 24rpx;
        color: #6c757d;
        font-weight: 400;
      }
    }
  }

  // 表单内容
  .login-form-content {
    .input-item {
      margin-bottom: 24rpx;

      &:last-child {
        margin-bottom: 0;
      }

      .input-wrapper {
        position: relative;
        display: flex;
        align-items: center;
        background: rgba(255, 255, 255, 0.9);
        border: 2rpx solid #e0e0e0;
        border-radius: 12rpx;
        transition: all 0.3s ease;
        overflow: hidden;

        &:focus-within {
          border-color: #667eea;
          background: #ffffff;
          box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.2),
            inset 0 1rpx 3rpx rgba(255, 255, 255, 0.9);
          transform: translateY(-2rpx);
        }

        .input-icon {
          font-size: 40rpx;
          color: #7f8c8d;
          margin: 0 24rpx;
          transition: color 0.3s ease;
        }

        .modern-input {
          flex: 1;
          height: 96rpx;
          font-size: 30rpx;
          color: #2c3e50;
          background: rgba(255, 255, 255, 0.9);
          border: 2rpx solid #e0e0e0;
          border-radius: 12rpx;
          padding: 0 20rpx;
          outline: none;
          transition: all 0.3s ease;

          &::placeholder {
            color: #64748b;
            font-size: 28rpx;
          }

          &:focus {
            border-color: #667eea;
            background: #ffffff;
            box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.2),
              inset 0 1rpx 3rpx rgba(255, 255, 255, 0.9);
            transform: translateY(-2rpx);
          }

          &:focus + .input-icon {
            color: #3b82f6;
          }
        }
      }
    }

    .action-btn {
      margin-top: 48rpx;

      .modern-login-btn {
        width: 100%;
        height: 96rpx;
        background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
        border: none;
        border-radius: 16rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;
        overflow: hidden;
        transition: all 0.3s ease;
        box-shadow: 0 8rpx 32rpx rgba(59, 130, 246, 0.4);

        &:active {
          transform: translateY(2rpx);
          box-shadow: 0 4rpx 16rpx rgba(59, 130, 246, 0.3);
        }

        .btn-text {
          color: #ffffff;
          font-size: 32rpx;
          font-weight: 600;
          letter-spacing: 2rpx;
        }

        .btn-loading {
          position: absolute;
          right: 32rpx;
          width: 32rpx;
          height: 32rpx;
          border: 3rpx solid rgba(255, 255, 255, 0.3);
          border-top: 3rpx solid #ffffff;
          border-radius: 50%;
          animation: spin 1s linear infinite;
        }
      }
    }
  }

  // 网络配置
  .network-config {
    text-align: center;

    .network-header {
      margin-bottom: 24rpx;

      .network-title {
        display: block;
        font-size: 28rpx;
        color: #e2e8f0;
        font-weight: 500;
        margin-bottom: 4rpx;
      }

      .network-subtitle {
        display: block;
        font-size: 20rpx;
        color: #64748b;
      }
    }

    .network-env-selector {
      display: flex;
      justify-content: center;
      align-items: center;
      gap: 16rpx;

      .env-item {
        padding: 12rpx 24rpx;
        font-size: 24rpx;
        color: #94a3b8;
        background: rgba(255, 255, 255, 0.08);
        border-radius: 20rpx;
        border: 1px solid rgba(255, 255, 255, 0.1);
        cursor: pointer;
        transition: all 0.3s ease;
        white-space: nowrap;

        &:hover {
          background: rgba(59, 130, 246, 0.2);
          color: #e2e8f0;
          border-color: rgba(59, 130, 246, 0.3);
        }

        &.active {
          background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
          color: #ffffff;
          border-color: #3b82f6;
          box-shadow: 0 4rpx 16rpx rgba(59, 130, 246, 0.4);
        }

        &:active {
          transform: scale(0.95);
        }
      }
    }
  }

  // 底部版权信息
  .footer-section {
    position: relative;
    z-index: 2;
    text-align: center;
    padding: 0 40rpx;
    margin-top: -40rpx;

    .company-info {
      margin-bottom: 24rpx;

      .company-name {
        display: block;
        font-size: 32rpx;
        font-weight: 600;
        color: #ffffff;
        margin-bottom: 12rpx;
        letter-spacing: 1rpx;
      }

      .platform-info {
        display: block;
        font-size: 24rpx;
        color: #94a3b8;
        font-weight: 400;
      }
    }

    .footer-decoration {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 16rpx;

      .decoration-line {
        width: 80rpx;
        height: 2rpx;
        background: linear-gradient(
          90deg,
          transparent 0%,
          #3b82f6 50%,
          transparent 100%
        );
      }

      .decoration-dot {
        width: 8rpx;
        height: 8rpx;
        background: #3b82f6;
        border-radius: 50%;
        animation: pulse 2s ease-in-out infinite;
      }
    }
  }

  // 功能区域预留样式
  .feature-reserved-section {
    text-align: center;
    margin-top: 40rpx;
    padding: 32rpx;
    background: rgba(255, 255, 255, 0.05);
    border-radius: 24rpx;
    border: 1px solid rgba(255, 255, 255, 0.1);
    backdrop-filter: blur(10px);
    min-height: 100rpx;
  }

  // 动画
  @keyframes float {
    0%,
    100% {
      transform: translateY(0px);
    }
    50% {
      transform: translateY(-20px);
    }
  }

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }

  @keyframes pulse {
    0%,
    100% {
      opacity: 1;
    }
    50% {
      opacity: 0.5;
    }
  }
}
</style>
